package com.sansui.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @name: ControllerExceptionHandler
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-03-16 21:38
 * 自定义异常拦截器
 **/

@ControllerAdvice
public class ControllerExceptionHandler {


    /*
    * @ControllerAdvice
    * Controller增强器,可对controller中被 @RequestMapping注解的方法加一些逻辑处理
    * */

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e)throws Exception{
        /*记录异常信息*/
        logger.error("Requst URL : {}，Exception : {}", request.getRequestURL(),e);

        /*过滤标记不用处理的异常*/
        //过滤掉NotFoundException标记的异常，交给springboot 本身去处理
        /*如果不为空 抛出异常*/
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }
        /*返回错误页面*/
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("url",request.getRequestURL());//获取url
        modelAndView.addObject("exception", e);//获取异常信息
        modelAndView.setViewName("error/error");//指定返回页面
        return modelAndView;
    }


}
